package com.shuqi.service;

import java.util.Date;
import java.util.List;

import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.SystemClock;

import com.shuqi.application.ShuqiApplication;
import com.shuqi.common.CheckBookMarkUpdate;
import com.shuqi.common.Config;
import com.shuqi.common.ConfigVersion;
import com.shuqi.common.CheckBookMarkUpdate.CheckBookMarkUpdateLinstener;
import com.shuqi.common.Constant;
import com.shuqi.common.FunctionsSwitch;
import com.shuqi.common.utils.Log4an;
import com.shuqi.controller.Loading;
import com.shuqi.controller.R;
import com.shuqi.model.bean.CheckBookUpdateInfo;
import com.shuqi.model.manager.MyAccountManager;
import com.shuqi.model.sharedprefs.SpConfig;
import com.shuqi.statistics.StatisticsEventID;
import com.shuqi.statistics.StatisticsUtils;

/**
 * 通知栏提醒服务 <br>
 * intent int 参数名:INTENT_NAME_ACTION <br>
 * INTENT_NAME_ACTION 对应的值：ACTION_*** 控制是否强制联网检查
 */
public class CheckMarksUpdateService extends Service {

    /** 控制检查的intent参数值：跳过检查，重置闹钟服务 */
    public static final int ACTION_JUMPCHECK = 0;
    /** 控制检查的intent参数值：强制检查，重置闹钟服务 */
    public static final int ACTION_FORCECHECK = 1;

    /** 两次检查书签更新之间的：间隔时间 单位：ms */
    private static final long TIME_INTERVAL = 2 * 60 * 60 * 1000;// 2小时

    private static final String logTag = "CheckMarksUpdateService";

    private Handler handler = new Handler();

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    /** 查看是否需要检查更新并重设闹钟 */
    @Override
    public void onStart(final Intent intent, int startId) {
        Log4an.e(logTag, "service start");
        
        //0:00-6:00 不推送
        Date date = new Date();
        if(date.getHours() <= 5 || ShuqiApplication.shuQiIsRunning()){
            Log4an.e(logTag, "service return, for hours="+date.getHours() + " or "+ShuqiApplication.shuQiIsRunning());
            resetAlarm(this);
            stopSelf();
            return;
        }
        if(!isNeedCheck()){
            stopSelf();
            return;
        }
        
        if (ConfigVersion.hasNull()) {
            ConfigVersion.setTelInfos(this, Config.ROOT_PATH, Config.VERSION_INFO, Config.SOFT_ID,
                    Config.MIN_SDK_VERSION, 0, MyAccountManager.getInstance(this).getUserId(),
                    MyAccountManager.getInstance(this).getSession());
        }
        
        // 如果软件已开启，则两个小时后启动
        // 如果软件未开启，联网检查书籍更新
        if (!ShuqiApplication.shuQiIsRunning()) {
            Log4an.e(logTag, "软件未开启，开始检查更新...");
            CheckBookMarkUpdateLinstener linstener = new CheckBookMarkUpdateLinstener() {
                @Override
                public void onFinish(boolean isAllSucces,int resultType, final List<CheckBookUpdateInfo> list) {
                    if (resultType == CheckBookMarkUpdate.TYPE_CHECKRESULT_HASUPDATE) {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                if(list!=null && list.size()>0){
                                    Log4an.e(logTag, "书签书籍有更新:size="+list.size()+", 书旗运行状态:"+ShuqiApplication.shuQiIsRunning());
                                    if (!ShuqiApplication.shuQiIsRunning()) {
                                        StatisticsUtils.onEvent(StatisticsEventID.PUSH_MESSAGE_UPDATE_NOTICE);
                                        showNotify("书旗小说："+list.size()+"本书有更新", getBookNames(list));
                                    }
                                }
                            }
                        });
                    }
                    if(isAllSucces){
                        SpConfig.getInstance().saveUpdateBookMarkTime();
                    }
                    resetAlarm(CheckMarksUpdateService.this);//放到了检查类里面
                    stopSelf();
                }
            };
            CheckBookMarkUpdate.getInstance().checkBookMarksUpdate(getApplicationContext(), linstener);
            
        } else {
            resetAlarm(this);
            Log4an.e(logTag, "软件已经开启，不检查更新");
            stopSelf();
        }
        super.onStart(intent, startId);
    }

    @Override
    public void onDestroy() {
        Log4an.e(logTag, "service服务结束");
        super.onDestroy();
    }
    
    /**获取N个书名《书名》*/
    private String getBookNames(List<CheckBookUpdateInfo> list){
        StringBuilder namesStr = new StringBuilder(20);
        if(list!=null && list.size()>0){
            for (int i = 0; i < list.size(); i++) {
                if(i == 5){
                    namesStr.append("...");
                    break;
                }
                namesStr.append("《"+list.get(i).getBookName()+"》");
            }
        }
        return namesStr.toString();
    }

    /**
     * 设置闹钟
     * 
     * @param nextStartTime 服务下次开启时候的时间
     * @param interval 两次的间隔开启时间
     */
    private static boolean resetAlarm(Context context) {
        Log4an.i(logTag, "reset alarm service");
        Intent intent = new Intent(context, CheckMarksUpdateService.class);
        PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0);

        AlarmManager alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
        // 取消旧闹钟
        try {
            alarmManager.cancel(pendingIntent);
        } catch (Exception e) {
            Log4an.d(logTag, "取消旧闹钟失败");
        }
        if (!FunctionsSwitch.isNotificationOpen(context)) {
            return false;
        }
//        old：使用系统时间唤醒闹钟，到指定的系统时间就会唤醒，该方法对某些手机不适用：华为、小米等
//        long nextStartTime = System.currentTimeMillis() + TIME_INTERVAL;
//        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, nextStartTime, TIME_INTERVAL,pendingIntent);
        //new：使用开机时间唤醒闹钟，必须经过指定毫秒数才会唤醒
        long currentTime = SystemClock.elapsedRealtime();
        long nextStartTime = currentTime + TIME_INTERVAL;
        alarmManager.set(AlarmManager.ELAPSED_REALTIME, nextStartTime,pendingIntent);
        // 类型、下次触发的时间，间隔时间、延迟意图
        Log4an.i(logTag, "reset service success 当前时间 "+currentTime+" 下次启动时间"
                +nextStartTime+" 大约 "+(TIME_INTERVAL/1000)+" 秒之后启动");
        return true;
    }

    public static boolean startCheckBookMarksUpdate(Context content) {
        return resetAlarm(content);
    }

    /** 取消闹钟服务：检查更新并通知栏提醒功能 */
    public static boolean cancelCheckBookMarksUpdate(Context content) {
        Intent intent = new Intent(content, CheckMarksUpdateService.class);
        PendingIntent pendingIntent = PendingIntent.getService(content, 0, intent, 0);
        AlarmManager alarmManager = (AlarmManager) content.getSystemService(ALARM_SERVICE);
        // 取消旧闹钟
        try {
            alarmManager.cancel(pendingIntent);
            Log4an.d(logTag, "取消书籍检查更新提醒功能成功");
            return true;
        } catch (Exception e) {
            Log4an.d(logTag, "取消书籍检查更新提醒功能失败");
            return false;
        }
    }

    /** 显示通知栏提示内容 */
    private void showNotify(String title, String content) {
        // Notification管理器：设置一个唯一的ID，随便设置
        Notification notification =
                new Notification(R.drawable.icon, title, System.currentTimeMillis());
        notification.flags = Notification.FLAG_AUTO_CANCEL;
        // 后面的参数分别是显示在顶部通知栏的小图标，小图标旁的文字（短暂显示会自动消失）系统当前时间（不明白这个有什么用）
        notification.defaults = Notification.DEFAULT_SOUND;
        // 这是设置通知是否同时播放声音或振动，声音为Notification.DEFAULT_SOUND
        // 振动为Notification.DEFAULT_VIBRATE;
        // 全部为Notification.DEFAULT_ALL
        // 如果是振动或者全部，必须在AndroidManifest.xml加入振动权限
        Intent intent = new Intent();
        String pn = getPackageName();
        ComponentName componentName = new ComponentName(pn, Loading.class.getName());
        // 可根据需求跳转到不同的activity(目前是测试,跳转到loading界面)
        intent.putExtra("push_update", "open");
        intent.setComponent(componentName);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.setAction(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.putExtra(Loading.INTENT_ACTIONTYPE, Loading.ACTIONTYPE_OPENSHELF);
        PendingIntent pt = 
                PendingIntent.getActivity(CheckMarksUpdateService.this, -100, intent,
                        PendingIntent.FLAG_UPDATE_CURRENT);
        // 点击通知后的动作，这里是转回main 这个Acticity
        notification.setLatestEventInfo(CheckMarksUpdateService.this, title, content, pt);
        ((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).notify(
                Constant.NOTIFICATION_ID_BOOKMARK_HAVEUPDATE, notification);
    }

    /** 关闭通知栏 */
    public static final void closeNotification(Context context) {
        ((NotificationManager) context.getSystemService(NOTIFICATION_SERVICE))
                .cancel(Constant.NOTIFICATION_ID_BOOKMARK_HAVEUPDATE);
    }

    /***
     * 对比上次价差的时间当前是否需要检查更新
     * @return
     */
    public static boolean isNeedCheck(){
        long lastTime = SpConfig.getInstance().getLastUpdateBookMarkTime();
        long curTime = System.currentTimeMillis();
        long intervalTime = curTime - lastTime;
        boolean isNeed = intervalTime < 0 || intervalTime > TIME_INTERVAL;
        Log4an.e(logTag,(isNeed?"需要":"不需要")+"检查 更新。 lastTime="+lastTime+" curTime="+curTime+" intervalTime="+(intervalTime/1000)+"秒");
        return isNeed;
    }
    
}
